package com.cindata

import com.cindata.dictionary.EvaluateDict
import com.cindata.dictionary.ExecStatusDict
import com.cindata.dictionary.ImportFileTypeDict
import groovy.transform.ToString

@ToString(includes = ["batchNumber", "estateNum", "matchNum"], includeNames = true, includePackage = false)
class ContactImportBatch
{

    String batchNumber
    Account account

    Integer count = 0
    Integer dealCount = 0

    ExecStatusDict status

    Date createdDate = new Date()
    Date modifiedDate
    User createBy
    User modifyBy
    Integer isDeleted = 0

    static mapping = {
        autowire true
    }

    static constraints = {
        batchNumber maxSize: 128, nullable: true, blank: true
        status maxSize: 10, nullable: true, blank: true

        account nullable: true, blank: true

        status nullable: true, blank: true

        createdDate nullable: true, blank: true
        modifiedDate nullable: true, blank: true
        createBy nullable: true, blank: true
        modifyBy nullable: true, blank: true
        isDeleted maxSize: 5, nullable: true, blank: true
    }

    def springSecurityService

    def beforeInsert()
    {
        def username = springSecurityService?.getPrincipal()?.username
        createBy = User.findByUsername(username)
    }

    def beforeUpdate()
    {
        modifiedDate = new Date()
        def username = springSecurityService?.getPrincipal()?.username
        modifyBy = User.findByUsername(username)
    }


    def updateCount()
    {
        def successCount = ContactImport.countByBatchAndEvaluateStatue(this, ExecStatusDict.SUCCESS())
        def failureCount = ContactImport.countByBatchAndEvaluateStatue(this, ExecStatusDict.FAILURE())
        this.dealCount = successCount + failureCount
        if (successCount + failureCount == this.count)
        {
            if (failureCount == this.count)
            {
                this.status = ExecStatusDict.FAILURE()
            }
            else if (failureCount > 0)
            {
                this.status = ExecStatusDict.PARTFAILURE()
            }
            else
            {
                this.status = ExecStatusDict.SUCCESS()
            }
        }
        this.save()
    }

}
